package net;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.Charset;

public class ChatClient implements PropertyChangeListener{
	InputStream in;
	OutputStream out;
	boolean isAlive = true;
	int port = 9099;
	Socket socket;
	ClientService clientService;
	
	public ChatClient(){
		try {
			socket = new Socket("127.0.0.1", port);
			clientService = new ClientService(this);
			Thread t = new Thread(clientService);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void propertyChange(PropertyChangeEvent e) {
		// TODO Auto-generated method stub
		String msg = (String)e.getNewValue();
		System.out.println(msg);
	}
	
	public synchronized void sendMessage(String msg){
		try{
			out.write(msg.getBytes(Charset.forName("utf-8")));
		}catch(IOException ex){}
	}
	
	class ClientService implements Runnable{
		PropertyChangeListener _handler;
		ClientService(PropertyChangeListener hl){
			_handler = hl;
		}
		
		public void run(){
			byte[] buf = new byte[512];
			int read;
			try{
				while( (read=in.read(buf))>=0  && isAlive){
					if(read>0){
						String msg = new String(buf, 0, read, Charset.forName("utf-8"));
						_handler.propertyChange(new PropertyChangeEvent(ClientService.this, 
								"message", "", msg));
					}
				}
			}catch(IOException ex){}
		}
	}

}
